<!doctype html>
<html lang="en-us">
<head>

    <meta charset="utf-8">
    <meta name="generator" content="Hugo 0.59.1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>SpringSecurity自定义认证结果处理 | 林贤钦</title>
    <meta property="og:title" content="SpringSecurity自定义认证结果处理 - 林贤钦">
    <meta property="og:type" content="article">
        
    <meta property="article:published_time" content="2020-03-16T11:05:29&#43;08:00">
        
        
    <meta property="article:modified_time" content="2020-03-16T11:05:29&#43;08:00">
        
    <meta name="Keywords" content="java,博客,项目管理,软件架构,公众号,小程序">
    <meta name="description" content="SpringSecurity自定义认证结果处理">
        
    <meta name="author" content="林贤钦">
    <meta property="og:url" content="http://linxianqin.gitee.io/post/springSecurity%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AE%A4%E8%AF%81%E7%BB%93%E6%9E%9C%E5%A4%84%E7%90%86/">
    <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="/css/normalize.css">
    
        <link rel="stylesheet" href="/css/prism.css">
    
    <link rel="stylesheet" href="/css/style.css">
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    


    
    
</head>

<body>
<header id="header" class="clearfix">
	<div class="container">
        <div class="col-group">
            <div class="site-name ">
                
                    <a id="logo" href="http://linxianqin.gitee.io">
                        林贤钦
                    </a>
                
                <p class="description">专注于Java、微信小程序、移动互联网、项目管理、软件架构</p>
            </div>
            <div>
                <nav id="nav-menu" class="clearfix">
                    <a class="current" href="http://linxianqin.gitee.io">首页</a>
                    
                    <a  href="http://linxianqin.gitee.io/archives/" title="归档">归档</a>
                    
                    <a  href="http://linxianqin.gitee.io/about/" title="关于">关于</a>
                    
                </nav>
            </div>
        </div>
    </div>
</header>


<div id="body">
        
        
    <div class="container">
        <div class="col-group">

            <div class="col-8" id="main">
                <div class="res-cons">
                    <article class="post">
                        <header>
                            <h1 class="post-title">SpringSecurity自定义认证结果处理</h1>
                        </header>
                        <date class="post-meta meta-date">
                            2020年3月16日
                        </date>
                        
                        <div class="post-meta">
                            <span>|</span>
                            
                                <span class="meta-category"><a href="http://linxianqin.gitee.io/categories/springSecurity">springSecurity</a></span>
                            
                        </div>
                        
                        
                        <div class="post-meta">
                            <span id="busuanzi_container_page_pv">|<span id="busuanzi_value_page_pv"></span><span> 阅读</span></span>
                        </div>
                        
                        
                        <div class="post-content">
							<nav id="TableOfContents">
<ul>
<li>
<ul>
<li><a href="#一-自定义登录验证结果处理的应用场景">一、自定义登录验证结果处理的应用场景</a>
<ul>
<li><a href="#准备工作">准备工作</a></li>
<li><a href="#需求">需求</a></li>
</ul></li>
<li><a href="#二-说明">二、说明</a>
<ul>
<li><a href="#三-实现自定义登录验证结果处理配置">三、实现自定义登录验证结果处理配置</a>
<ul>
<li><a href="#自定义登录成功验证处理">自定义登录成功验证处理</a></li>
<li><a href="#同理-自定义登录失败验证处理">同理：自定义登录失败验证处理</a></li>
</ul></li>
</ul></li>
</ul></li>
</ul>
</nav>
                            

<h2 id="一-自定义登录验证结果处理的应用场景">一、自定义登录验证结果处理的应用场景</h2>

<p>1、不同的人登录之后，看到不同的页面。</p>

<p>2、前后端分离的应用，期望响应结果是json，而不是html页面。</p>

<h3 id="准备工作">准备工作</h3>

<ul>
<li>在formLogin的基础上增加5个类</li>
<li>自定义登录成功结果处理MyAuthenticationSuccessHandler</li>
<li>自定义登录失败结果处理MyAuthenticationFailureHandler</li>
<li>另外三个为json工具类</li>
</ul>

<h3 id="需求">需求</h3>

<ul>
<li>json显示登录成功或者登录失败</li>
</ul>

<h2 id="二-说明">二、说明</h2>

<ul>
<li>登录成功的自定义结果处理接口：AuthenticationSuccessHandler</li>
<li>登录失败的自定义结果处理接口：AuthenticationFailureHandler</li>
</ul>

<h3 id="三-实现自定义登录验证结果处理配置">三、实现自定义登录验证结果处理配置</h3>

<p>首先，json工具类的配置如下</p>

<p>1、AjaxResponse</p>

<pre><code class="language-java">import lombok.Data;

@Data
public class AjaxResponse {


    private boolean isok;
    private int code;
    private String message;
    private Object data;

    private AjaxResponse() {

    }

    //请求出现异常时的响应数据封装
    public static AjaxResponse error(CustomException e) {

        AjaxResponse resultBean = new AjaxResponse();
        resultBean.setIsok(false);
        resultBean.setCode(e.getCode());
        if(e.getCode() == CustomExceptionType.USER_INPUT_ERROR.getCode()){
            resultBean.setMessage(e.getMessage());
        }else if(e.getCode() == CustomExceptionType.SYSTEM_ERROR.getCode()){
            resultBean.setMessage(e.getMessage() + &quot;,系统出现异常，请联系管理员电话：1375610xxxx进行处理!&quot;);
        }else{
            resultBean.setMessage(&quot;系统出现未知异常，请联系管理员电话：13756108xxx进行处理!&quot;);
        }
        return resultBean;
    }

    public static AjaxResponse success() {
        AjaxResponse resultBean = new AjaxResponse();
        resultBean.setIsok(true);
        resultBean.setCode(200);
        resultBean.setMessage(&quot;success&quot;);
        return resultBean;
    }

    public static AjaxResponse success(Object data) {
        AjaxResponse resultBean = new AjaxResponse();
        resultBean.setIsok(true);
        resultBean.setCode(200);
        resultBean.setMessage(&quot;success&quot;);
        resultBean.setData(data);
        return resultBean;
    }

    public boolean isIsok() {
        return isok;
    }

    public void setIsok(boolean isok) {
        this.isok = isok;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}
</code></pre>

<p>2、CustomException</p>

<pre><code class="language-java">public class CustomException extends RuntimeException {
    //异常错误编码
    private int code ;
    //异常信息
    private String message;

    private CustomException(){}

    public CustomException(CustomExceptionType exceptionTypeEnum, String message) {
        this.code = exceptionTypeEnum.getCode();
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }
}
</code></pre>

<p>3、CustomExceptionType</p>

<pre><code class="language-java">public enum CustomExceptionType {
    USER_INPUT_ERROR(400,&quot;用户输入异常&quot;),
    SYSTEM_ERROR (500,&quot;系统服务异常&quot;),
    OTHER_ERROR(999,&quot;其他未知异常&quot;);

    CustomExceptionType(int code, String typeDesc) {
        this.code = code;
        this.typeDesc = typeDesc;
    }

    private String typeDesc;//异常类型中文描述

    private int code; //code

    public String getTypeDesc() {
        return typeDesc;
    }

    public int getCode() {
        return code;
    }
}
</code></pre>

<h4 id="自定义登录成功验证处理">自定义登录成功验证处理</h4>

<p>MyAuthenticationSuccessHandler类</p>

<pre><code>@Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Value(&quot;${spring.security.loginType}&quot;)
    private String loginType;

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication)
            throws ServletException, IOException {
        if (loginType.equalsIgnoreCase(&quot;JSON&quot;)){
            response.setContentType(&quot;application/json;charset=UTF-8&quot;);
     response.getWriter().write(objectMapper.writeValueAsString(AjaxResponse.success()));
        }else{
            //调用父类方法，跳转到登录之前的请求页面
            super.onAuthenticationSuccess(request,response,authentication);
        }
    }
}
</code></pre>

<p>然后在SecurityConfig的配置中增加</p>

<pre><code class="language-java">@Resource
MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
</code></pre>

<p>在protected void configure(HttpSecurity http) 中修改</p>

<pre><code>.defaultSuccessUrl(&quot;/index&quot;)
</code></pre>

<p>为</p>

<pre><code>.successHandler(myAuthenticationSuccessHandler)//默认登录成功自定义结果,不能与defaultSuccessUrl同时使用
</code></pre>

<p>这样在登录成功的时候会显示</p>

<pre><code class="language-Json">{&quot;isok&quot;:true,&quot;code&quot;:200,&quot;message&quot;:&quot;success&quot;,&quot;data&quot;:null}
</code></pre>

<h4 id="同理-自定义登录失败验证处理">同理：自定义登录失败验证处理</h4>

<p>MyAuthenticationFailureHandler 类</p>

<pre><code>@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Value(&quot;${spring.security.loginType}&quot;)
    private String loginType;

    private static ObjectMapper objectMapper = new ObjectMapper();
    
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {
        String errorMsg = &quot;用户名或者密码输入错误!&quot;;
        if(exception instanceof SessionAuthenticationException){
            errorMsg = exception.getMessage();
        }
        if(loginType.equalsIgnoreCase(&quot;JSON&quot;)){
            response.setContentType(&quot;application/json;charset=UTF-8&quot;);
            response.getWriter().write(objectMapper.writeValueAsString(
                    AjaxResponse.error(new CustomException(
                            CustomExceptionType.USER_INPUT_ERROR,
                            errorMsg))
            ));
        }else{
            //跳转到登陆页面
            super.onAuthenticationFailure(request,response,exception);
        }
    }
}
</code></pre>

<p>然后在SecurityConfig的配置中增加</p>

<pre><code class="language-java">@Resource
MyAuthenticationFailureHandler myAuthenticationFailureHandler;
</code></pre>

<p>在protected void configure(HttpSecurity http) 中修改</p>

<pre><code>.failureUrl(&quot;/login.html&quot;)//登录失败也页面
</code></pre>

<p>为</p>

<pre><code>.failureHandler(myAuthenticationFailureHandler)//默认登录失败自定义结果,不能与failureUrl同时使用
</code></pre>

<p>这样在登录失败的时候会显示</p>

<pre><code class="language-Json">{&quot;isok&quot;:false,&quot;code&quot;:400,&quot;message&quot;:&quot;用户名或者密码输入错误!&quot;,&quot;data&quot;:null}
</code></pre>

                        </div>
						 
                        
<div class="post-archive">
    <ul class="post-copyright">
        <li><strong>原文作者：</strong><a rel="author" href="http://linxianqin.gitee.io">林贤钦</a></li>
        <li style="word-break:break-all"><strong>原文链接：</strong><a href="http://linxianqin.gitee.io/post/springSecurity%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AE%A4%E8%AF%81%E7%BB%93%E6%9E%9C%E5%A4%84%E7%90%86/">http://linxianqin.gitee.io/post/springSecurity%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AE%A4%E8%AF%81%E7%BB%93%E6%9E%9C%E5%A4%84%E7%90%86/</a></li>
        <li><strong>版权声明：</strong>本作品采用<a rel="license" href="https://linxianqin.gitee.io">知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议</a>进行许可，非商业转载请注明出处（作者，原文链接），商业转载请联系作者获得授权。</li>
    </ul>
</div>
<br/>



                        

<div class="post-archive">
    <h2>See Also</h2>
    <ul class="listing">
        
        <li><a href="/post/springSecurity%E4%B8%ADformLogin%E7%99%BB%E5%BD%95%E8%AE%A4%E8%AF%81%E6%A8%A1%E5%BC%8F/">SpringSecurity中formLogin登录认证模式</a></li>
        
        <li><a href="/post/java8%E6%96%B0%E7%89%B9%E6%80%A7Lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F/">Java8新特性Lambda表达式</a></li>
        
        <li><a href="/post/java8%E6%96%B0%E7%89%B9%E6%80%A7stream%E6%B5%81/">Java8新特性stream流</a></li>
        
        <li><a href="/post/yml%E6%96%87%E4%BB%B6%E7%9A%84%E7%AE%80%E4%BB%8B/">Yml文件的简介</a></li>
        
        <li><a href="/post/json%E4%B8%8Ejava%E6%A0%BC%E5%BC%8F%E7%9B%B8%E4%BA%92%E8%BD%AC%E5%8C%96/">json与java格式相互转化</a></li>
        
    </ul>
</div>


                        <div class="post-meta meta-tags">
                            
                            <ul class="clearfix">
                                
                                <li><a href="http://linxianqin.gitee.io/tags/spring">spring</a></li>
                                
                                <li><a href="http://linxianqin.gitee.io/tags/java">java</a></li>
                                
                            </ul>
                            
                        </div>
                    </article>
                    
    

    
    
    <div class="post bg-white">
      <script src="https://utteranc.es/client.js"
            repo= "757610938/hugo-blogs-utterances"
            issue-term="pathname"
            theme="github-light"
            crossorigin="anonymous"
            async>
      </script>
    </div>
    
                </div>
            </div>
            <div id="secondary">
    <section class="widget">
        <form id="search" action="//www.google.com/search" method="get" accept-charset="utf-8" target="_blank" _lpchecked="1">
      
      <input type="text" name="q" maxlength="20" placeholder="Search">
      <input type="hidden" name="sitesearch" value="http://linxianqin.gitee.io">
      <button type="submit" class="submit icon-search"></button>
</form>
    </section>
    
    <section class="widget">
        <h3 class="widget-title">最近文章</h3>
<ul class="widget-list">
    
    <li>
        <a href="http://linxianqin.gitee.io/post/java-%E5%8F%8D%E5%B0%84/" title="Java 反射">Java 反射</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/java-%E9%93%BE%E8%A1%A8/" title="Java 链表">Java 链表</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/%E7%9F%AD%E4%BF%A1%E6%B3%A8%E5%86%8C%E5%92%8C%E5%BE%AE%E4%BF%A1%E7%99%BB%E5%BD%95%E7%9A%84%E5%AE%9E%E7%8E%B0/" title="短信注册和微信登录的实现">短信注册和微信登录的实现</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/OAuth2.0%E8%AE%A4%E8%AF%81%E6%8E%88%E6%9D%83%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95/" title="OAuth2.0认证授权单点登录">OAuth2.0认证授权单点登录</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/Nacos%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83/" title="Nacos服务注册中心">Nacos服务注册中心</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/SpringCloud%E5%BE%AE%E6%9C%8D%E5%8A%A1/" title="SpringCloud微服务">SpringCloud微服务</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/%E9%98%BF%E9%87%8C%E4%BA%91%E8%A7%86%E9%A2%91%E7%82%B9%E6%92%AD%E6%9C%8D%E5%8A%A1/" title="阿里云视频点播服务前后端实现">阿里云视频点播服务前后端实现</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/%E9%98%9F%E5%88%97/" title="队列">队列</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/%E7%A8%80%E7%96%8F%E6%95%B0%E7%BB%84/" title="稀疏数组">稀疏数组</a>
    </li>
    
    <li>
        <a href="http://linxianqin.gitee.io/post/%E9%98%BF%E9%87%8C%E4%BA%91EasyExcel%E5%AE%9E%E7%8E%B0%E5%90%8E%E7%AB%AF%E5%AF%B9Excel%E7%9A%84%E8%AF%BB%E5%86%99%E6%93%8D%E4%BD%9C/" title="使用阿里云EasyExcel实现后端对Excel的读写操作">使用阿里云EasyExcel实现后端对Excel的读写操作</a>
    </li>
    
</ul>
    </section>

    

    <section class="widget">
        <h3 class="widget-title">分类</h3>
<ul class="widget-list">
    
    <li><a href="http://linxianqin.gitee.io/categories/JWT/">JWT (2)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/hugo/">hugo (2)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/java/">java (18)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/java8/">java8 (1)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/springCloud/">springCloud (2)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/springSecurity/">springSecurity (4)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/vue/">vue (5)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/yml/">yml (1)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">数据结构 (3)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/%E8%BD%AF%E4%BB%B6%E6%B5%8B%E8%AF%95/">软件测试 (1)</a></li>
    
    <li><a href="http://linxianqin.gitee.io/categories/%E9%98%BF%E9%87%8C%E4%BA%91/">阿里云 (4)</a></li>
    
</ul>
    </section>

    <section class="widget">
        <h3 class="widget-title">标签</h3>
<div class="tagcloud">
    
    <a href="http://linxianqin.gitee.io/tags/JWT/">JWT</a>
    
    <a href="http://linxianqin.gitee.io/tags/hugo/">hugo</a>
    
    <a href="http://linxianqin.gitee.io/tags/java/">java</a>
    
    <a href="http://linxianqin.gitee.io/tags/java8/">java8</a>
    
    <a href="http://linxianqin.gitee.io/tags/spring/">spring</a>
    
    <a href="http://linxianqin.gitee.io/tags/springBoot/">springBoot</a>
    
    <a href="http://linxianqin.gitee.io/tags/springCloud/">springCloud</a>
    
    <a href="http://linxianqin.gitee.io/tags/ssm/">ssm</a>
    
    <a href="http://linxianqin.gitee.io/tags/vue/">vue</a>
    
    <a href="http://linxianqin.gitee.io/tags/yml/">yml</a>
    
    <a href="http://linxianqin.gitee.io/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">数据结构</a>
    
    <a href="http://linxianqin.gitee.io/tags/%E8%BD%AF%E4%BB%B6%E6%B5%8B%E8%AF%95/">软件测试</a>
    
    <a href="http://linxianqin.gitee.io/tags/%E9%98%BF%E9%87%8C%E4%BA%91/">阿里云</a>
    
</div>
    </section>

    
<section class="widget">
    <h3 class="widget-title">友情链接</h3>
    <ul class="widget-list">
        
        <li>
            <a target="_blank" href="https://www.cnki.net" title="中国知网">中国知网</a>
        </li>
        
        <li>
            <a target="_blank" href="https://linxianqin.com" title="个人的另一个博客网站(国内加载慢)">个人的另一个博客网站(国内加载慢)</a>
        </li>
        
    </ul>
</section>


    <section class="widget">
        <h3 class="widget-title">其它</h3>
        <ul class="widget-list">
            <li><a href="http://linxianqin.gitee.io/index.xml">文章 RSS</a></li>
        </ul>
    </section>
</div>
        </div>
    </div>
</div>
<footer id="footer">
    <div class="container">
        &copy; 2020 <a href="http://linxianqin.gitee.io">林贤钦 By 林贤钦</a>.
        Powered by <a rel="nofollow noreferer noopener" href="https://gohugo.io" target="_blank">Hugo</a>.
        <a href="https://www.flysnow.org/" target="_blank">Theme</a> based on <a href="https://github.com/rujews/maupassant-hugo" target="_blank">maupassant</a>.
        
    </div>
</footer>


    
    <script type="text/javascript">
        
        (function () {
            $("pre code").parent().addClass("line-numbers")
        }());

        window.MathJax = {
            tex2jax: {
                inlineMath: [['$', '$']],
                processEscapes: true
                }
            };
    </script>
    <script type="text/javascript" src="/js/prism.js" async="true"></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>


<a id="rocket" href="#top"></a>
<script type="text/javascript" src="/js/totop.js?v=0.0.0" async=""></script>

<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
	window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
	ga('create', 'GA ID', 'auto');
	
	ga('send', 'pageview');
}
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>



    <script type="text/javascript" src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>




</body>
</html>
